import React, { useState, useEffect } from 'react';
import { CurModel, User } from '../cache';
import { Redirect } from 'react-router-dom';
import { DlgAdm } from 'manage/user/base';
import { cline, useCmd, WaitUmd, LayFrame, ListBox, uDb, for_obj, obj_empty, loc, obj_str } from 'sui';
import { Tech, NavTech } from 'tech/index';
import { Tool, NavTool } from 'tool/index';
import { Manage, NavManage } from 'manage/index';
import { Equip, NavEquip } from 'equip/index';
import { Oil, NavOil } from 'oil/index';
import { NavOuthouse, Outhouse } from 'outhouse/index';
import { Part, NavPart } from 'part/index';
import { WareHouse, NavWareHouse } from 'warehouse/index';
import { Stock, NavStock } from 'stock/index';
import { Away, NavAway } from 'away/index';
import { Goods, NavGoods } from 'goods/index';
import { Task, NavTask } from 'task/index';
import { CenSus, NavCenSus } from 'census/index';
import { Trace, NavTrace } from 'trace/index';
import { Pair, NavPair } from 'pair/index';
import { Pick, NavPick } from 'pick/index';
import { Side, NavSide } from 'side/index';
import { NavSupply, Supply } from 'supply/index';
import { NavTest, Test } from 'test/index';
import { NavQa, Qa } from 'qa/index';
import { NavNg, Ng } from 'ng/index';
import { NavStuff, Stuff } from 'stuff/index';
import { NavDefect, Defect } from 'defect/index';
import { NavSale, Sale } from 'sale/index';
import { NavBuy, Buy } from 'buy/index';
import { NavKind, Kind } from 'kind/index';

const g_model = () => {
    return [
        {id: "tech",        view: Tech,         nav: NavTech,       desc: loc("l_320")},
        {id: "task",        view: Task,         nav: NavTask,       desc: loc("l_321")},
        {id: "sale",        view: Sale,         nav: NavSale,       desc: loc("l_176")},
        {id: "buy",         view: Buy,          nav: NavBuy,        desc: loc("l_534")},
        {id: "census",      view: CenSus,       nav: NavCenSus,     desc: loc("l_443")},
        {id: "pick",        view: Pick,         nav: NavPick,       desc: loc("l_885")},
        {id: "pair",        view: Pair,         nav: NavPair,       desc: loc("l_689")},
        {id: "supply",      view: Supply,       nav: NavSupply,     desc: loc("l_549")},
        {id: "ng",          view: Ng,           nav: NavNg,         desc: loc("l_811")},
        {id: "stuff",       view: Stuff,        nav: NavStuff,      desc: loc("l_720")},
        {id: "kind",        view: Kind,         nav: NavKind,       desc: loc("l_724")},
        {id: "tool",        view: Tool,         nav: NavTool,       desc: loc("l_143")},
        {id: "warehouse",   view: WareHouse,    nav: NavWareHouse,  desc: loc("l_722")},
        {id: "side",        view: Side,         nav: NavSide,       desc: loc("l_445")},
        {id: "outhouse",    view: Outhouse,     nav: NavOuthouse,   desc: loc("l_138")},
        {id: "test",        view: Test,         nav: NavTest,       desc: loc("l_769")},
        {id: "qa",          view: Qa,           nav: NavQa,         desc: loc("l_778")},
        {id: "defect",      view: Defect,       nav: NavDefect,     desc: loc("l_831")},
        {id: "part",        view: Part,         nav: NavPart,       desc: loc("l_135")},
        {id: "oil",         view: Oil,          nav: NavOil,        desc: loc("l_102")},
        {id: "stock",       view: Stock,        nav: NavStock,      desc: loc("l_323")},
        {id: "away",        view: Away,         nav: NavAway,       desc: loc("l_819")},
        {id: "goods",       view: Goods,        nav: NavGoods,      desc: loc("l_850")},
        {id: "equip",       view: Equip,        nav: NavEquip,      desc: loc("l_687")},
        {id: "trace",       view: Trace,        nav: NavTrace,      desc: loc("l_324")},
        {id: "manage",      view: Manage,       nav: NavManage,     desc: loc("l_326")},
    ];
};

const ServerHome = () => {
    const [fin, setFin] = useState(false);
    const [app_title, appTitle] = useState("");
    const [mod, setMod] = useState(CurModel.getItem("cur-model", "tech"));
    const [auth, setAuth] = useState([]);
    const [cfg, setCfg] = useState(null);
    const [event, setEvent] = useState("");
    const [sideopen, openSide] = useState(true);
    const [open_adm, openAdm] = useState(false);

    const umd = useCmd();

    useEffect(() => {
        appTitle(loc("l_213"));

        if (cfg && cfg.set && cfg.set.title) {
            appTitle(cfg.set.title);
        }
    }, [cfg]);

    const modChange = (v) => {
        if (v === mod) {
            return;
        }

        CurModel.setItem("cur-model", v);
        setMod(v);
    };

    const get_line = () => {
        let line = CurModel.getLineDes();
        const ver = CurModel.get_ver();
        return [line, `V${ver}`];
    };

    useEffect(() => {
        const m = g_model();

        const filter_admin = (result) => m.filter(d => {
            const id = d.id;
            if (result[id]) {
                return true;
            }

            return false;
        });

        const filter = (result) => m.filter(d => {
            const id = d.id;
            for (let i = 0; i < result.length; i++) {
                if (id === result[i]) {
                    return true;
                }
            }

            return false;
        });

        uDb(null, "setting/get", {line: cline()}, r => {
            if (!obj_empty(r.db)) {
                for_obj(r.db, (k, v) => {
                    CurModel.set_db(k, v);
                });
            }

            setCfg(r);

            CurModel.set_client(obj_str(r, "client"));
            CurModel.set_log(obj_str(r, "piclog"));

            if (User.isAdmin()) {
                setAuth(filter_admin(r["mod"]));
            }
            else {
                const u = User.userAuth();
                const lst = u ? u.split(",") : [];
                setAuth(filter(lst));
            }
        });
    }, []);

    const view = () => {
        for (let i = 0; i < auth.length; i++) {
            const d = auth[i];
            const md = mod.split(".");
            if (d.id === md[0]) {
                const CurView = d.view;
                return <CurView cfg={cfg} mod={md[1]} event={event} setEvent={setEvent} sideopen={sideopen}/>;
            }
        }

        return null;
    };

    if (fin || !User.isLogin()) {
        if (fin) {
            User.LogOut();
        }

        return (<Redirect push to="/"/>);
    }

    const [line, ver] = get_line();

    const item = () => {
        if (!auth) {
            return null;
        }

        return auth.map(d => {
            const View = d.nav;
            return <View cfg={cfg} cur={mod} value={d.desc} uid={d.id} hcmd={modChange} key={d.id} event={event} setEvent={setEvent}/>;
        });
    };

    const hadm = (v) => {
        umd.startWait();

        uDb(null, "user/md",
            {
                line: cline(),
                sn: User.userName(),
                v: {
                    sn: User.userName(),
                    passwd: obj_str(v, "pass"),
                }
            },
            r => umd.endWait(), e => umd.setErr(loc("l_232")), true);
    };

    const Tool = () => <div className="text-white mr-4 text-base text-nowrap">{loc("l_329") + ", " + User.uName()}</div>;

    return (
        <LayFrame
            title={app_title}
            ver={ver}
            line={line}
            hlogout={() => setFin(true)}
            log={CurModel.get_log()}
            view={view}
            sideopen={sideopen}
            setOpen={openSide}
            huser={() => openAdm(true)}
            luser={loc("l_444")}
            tool={<Tool/>}>
            <ListBox>
                {item()}
            </ListBox>
            <DlgAdm open={open_adm} setOpen={openAdm} hcmd={hadm}/>
            <WaitUmd umd={umd}/>
        </LayFrame>
    );
};

export {ServerHome, g_model};
